package com.chen.facemanager.controller;

import com.chen.facemanager.bean.WxOrder;
import com.chen.facemanager.dao.WxOrderDao;
import com.chen.facemanager.service.impl.WXserviceImpl;
import com.chen.facemanager.util.ReturnModel;
import com.chen.facemanager.util.WxMD5Util;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Api(value = "/weixin", tags = "微信支付")
@RestController
@RequestMapping("/weixin")
public class WXPayController {

    @Autowired
    private WXserviceImpl wxPayService;


    /**
     * 统一下单
     * 官方文档:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_1
     */
    @ApiOperation(value = "统一下单", notes = "统一下单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", value = "用户id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "hid", value = "酒店id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "totalFee", value = "金额", required = true, dataType = "String"),
            @ApiImplicitParam(name = "attach", value = "附加信息", required = true, dataType = "String"),
            @ApiImplicitParam(name = "body", value = "支付信息", required = false, defaultValue = "身份核验服务费", dataType = "String"),
            @ApiImplicitParam(name = "type", value = "商品类型", required = false, defaultValue = "0", dataType = "String")
    })
    @RequestMapping("/order")
    public Map<String, String> wxPay(@RequestParam(value = "uid") String uid,
                                     @RequestParam(value = "hid",required = false) String hid,
                                     @RequestParam(value = "totalFee") String total_fee,
                                     @RequestParam(value = "attach") String attach,
                                     @RequestParam(value = "body", required = false, defaultValue = "身份核验服务费") String body,
                                     @RequestParam(value = "type", required = false, defaultValue = "0") String type
    ) throws Exception {

//        String attach= "{\"uid\":\""+uid+"\",\"hid\":\""+hid+"\"}";
        //请求预支付订单
        Map<String, String> result = wxPayService.dounifiedOrder(uid, hid, total_fee, attach, body, type);
        Map<String, String> map = new HashMap<>();

        WxMD5Util md5Util = new WxMD5Util();
        //返回APP端的数据
        //参加调起支付的签名字段有且只能是6个，分别为appid、partnerid、prepayid、package、noncestr和timestamp，而且都必须是小写
        //参加调起支付的签名字段有且只能是6个，分别为appid、partnerid、prepayid、package、noncestr和timestamp，而且都必须是小写
        //参加调起支付的签名字段有且只能是6个，分别为appid、partnerid、prepayid、package、noncestr和timestamp，而且都必须是小写
        map.put("appid", result.get("appid"));
        map.put("partnerid", result.get("mch_id"));
        map.put("prepayid", result.get("prepay_id"));
        map.put("package", "Sign=WXPay");
        map.put("noncestr", result.get("nonce_str"));
        map.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));//单位为秒
//      这里不要使用请求预支付订单时返回的签名
//      这里不要使用请求预支付订单时返回的签名
//      这里不要使用请求预支付订单时返回的签名
        map.put("sign", md5Util.getSign(map));
        map.put("extdata", attach);
        return map;
    }

    /**
     * 支付异步结果通知，我们在请求预支付订单时传入的地址
     * 官方文档 ：https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_7&index=3
     */

    @ApiOperation(value = "支付异步结果通知", notes = "支付异步结果通知")
    @RequestMapping(value = "/notify", method = {RequestMethod.GET, RequestMethod.POST})
    public String wxPayNotify(HttpServletRequest request, HttpServletResponse response) {
        String resXml = "";
        try {
            InputStream inputStream = request.getInputStream();
            //将InputStream转换成xmlString
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            resXml = sb.toString();
            String result = wxPayService.payBack(resXml);
            return result;
        } catch (Exception e) {
            System.out.println("微信手机支付失败:" + e.getMessage());
            String result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            return result;
        }
    }

    @ApiOperation(value = "统一下单ios", notes = "统一下单ios")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", value = "用户id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "hid", value = "酒店id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "totalFee", value = "金额", required = true, dataType = "String"),
            @ApiImplicitParam(name = "attach", value = "附加信息", required = true, dataType = "String"),
            @ApiImplicitParam(name = "body", value = "支付信息", required = false, defaultValue = "身份核验服务费", dataType = "String"),
            @ApiImplicitParam(name = "type", value = "商品类型", required = false, defaultValue = "0", dataType = "String"),

    })
    @PostMapping("/ios-order")
    public Map<String, String> wxPayIOS(@RequestParam(value = "uid") String uid,
                                        @RequestParam(value = "hid") String hid,
                                        @RequestParam(value = "totalFee") String total_fee,
                                        @RequestParam(value = "attach") String attach,
                                        @RequestParam(value = "body", required = false, defaultValue = "身份核验服务费") String body,
                                        @RequestParam(value = "type", required = false, defaultValue = "0") String type
    ) throws Exception {

        //请求预支付订单
        Map<String, String> result = wxPayService.dounifiedOrderIOS(uid, hid, total_fee, attach, body, type);
        Map<String, String> map = new HashMap<>();

        WxMD5Util md5Util = new WxMD5Util();
        map.put("appid", result.get("appid"));
        map.put("partnerid", result.get("mch_id"));
        map.put("prepayid", result.get("prepay_id"));
        map.put("package", "Sign=WXPay");
        map.put("noncestr", result.get("nonce_str"));
        map.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));//单位为秒
        map.put("sign", md5Util.getSign(map));
        map.put("extdata", attach);
        map.put("mweb_url", result.get("mweb_url"));
        return map;
    }
}

